package com.hitqz.robot.driver.util;


import com.hitqz.robot.api.common.entity.RobotMapPos;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.util.GeometricShapeFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Component("positionUtil")
@Slf4j
public class PositionUtil {

    @Value("${not-play-voice-radius:1}")
    private double notPlayVoiceRadius;
    private Polygon circle;

    @PostConstruct
    public void init() {
        new Thread(() -> {
            try {
                Thread.sleep(5000);
                RobotMapPos robotMapPos = KcToolkit.posMap.get(KcToolkit.chargePosCode);
                double centerX = Optional.ofNullable(robotMapPos).map(RobotMapPos::getPosX).orElse(0d);
                double centerY = Optional.ofNullable(robotMapPos).map(RobotMapPos::getPosY).orElse(0d);
                circle = createCircle(centerX, centerY, notPlayVoiceRadius, 32);
                log.info("init circle: ({},{}) radius:{}", centerX, centerY,notPlayVoiceRadius);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    /**
     * 判断点是否在圆里
     *
     * @return
     */
    public boolean checkPosition(double x, double y) {
        GeometryFactory gf = new GeometryFactory();
        Point testPoint1 = gf.createPoint(new Coordinate(x, y)); // 应该在圆内
        return isPointInCircle(testPoint1, circle);
    }


    // 创建圆形多边形
    public Polygon createCircle(double x, double y, double radius, int points) {
        GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
        shapeFactory.setNumPoints(points); // 设置多边形的边数(越多越接近圆)
        shapeFactory.setCentre(new Coordinate(x, y)); // 圆心坐标
        shapeFactory.setSize(radius * 2); // 直径
        return shapeFactory.createCircle();
    }

    // 判断点是否在圆内
    public static boolean isPointInCircle(Point point, Polygon circle) {
        return circle.contains(point);
    }

}
